package com.example.yunojcodesandbox.controller;

import com.example.yunojcodesandbox.JavaNativeCodeSandboxOld;
import com.example.yunojcodesandbox.model.ExecuteCodeRequest;
import com.example.yunojcodesandbox.model.ExecuteCodeResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
public class MainController {
    //调用鉴权请求头和密钥
    private static final String AUTH_REQUEST_HEADER = "auth";
    private static final String SECRET_KEY = "secret";
    @Resource
    private JavaNativeCodeSandboxOld javaNativeCodeSandbox;
    @GetMapping("/health")
    public String healthCheck() {
        return "ok";
    }
    /**
     * 执行代码
     *
     * @param executeCodeRequest
     * @return
     */
    @PostMapping("/executeCode")
    ExecuteCodeResponse executeCode(@RequestBody ExecuteCodeRequest executeCodeRequest, HttpServletRequest request,
                                    HttpServletResponse response) {
        //这里我要验证请求头
        String header = request.getHeader(AUTH_REQUEST_HEADER);
        if (!SECRET_KEY.equals(header)){
            response.setStatus(403);
            return null;
        }
        if (executeCodeRequest == null) {
            throw new RuntimeException("请求参数为空");
        }
        return javaNativeCodeSandbox.executeCode(executeCodeRequest);
    }

}
